﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ContractManager.BLL.Business;
using ContractManager.Common.Class;
using ContractManager.Common.FormBase;
using System.Windows.Forms;
using ContractManager.Entity;
using ContractManager.Entity.Base;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;

namespace ContractManager.Lists.Contracts
{
    public partial class FrmWorkflowDetail : XtraFormBase
    {
        #region "Private Variable"
        
        public bool SaveClose;
        public bool SaveNew;
        public bool OnlyView;
        public int MasterId;

        private readonly BackgroundWorker _loadworker = new BackgroundWorker();

       
        public List<Employees> LstEmployees = new List<Employees>();
        public DataTable DtContracts;
        
        #endregion

        #region "Form Construction"
        public FrmWorkflowDetail()
        {
            InitializeComponent();
            ClsVariable.DoubleBuffer(this);
            _loadworker.DoWork += loadworker_DoWork;
            _loadworker.RunWorkerCompleted += loadworker_RunWorkerCompleted;
        }
        #endregion

        #region "Private Method"

        private void BlankForm()
        {
            ResetControls();
            
            grdDetail.DataSource = ClsWorkflow.ListDetail(0);   
        }

        public void GetData()
        {
            if (!_loadworker.IsBusy)
            {
                _loadworker.RunWorkerAsync();
                ClsVariable.SetWaitDialogCaption(string.Format("Nạp danh sách {0}...", Text));
            }
        }

        private void LoadLookupData()
        {
            empSearchLookUpEdit.DataSource = LstEmployees;
            empSearchLookUpEdit.DisplayMember = "FullName";
            empSearchLookUpEdit.ValueMember = "ID";

            txtConDetId.Properties.DataSource = DtContracts;
            txtConDetId.Properties.DisplayMember = "ConDetContent";
            txtConDetId.Properties.ValueMember = "ConDetId";

            if (MasterId > 0) GetDetail();
        }

        private void GetDetail()
        {
            var detail = ClsWorkflow.SelectByPk(MasterId);
            if (detail != null)
            {
                txtWorkflowNo.EditValue = detail.WorkflowNo;
                txtWorkflowSymbol.EditValue = detail.WorkflowSymbol;
                txtWorkflowDate.EditValue = detail.WorkflowDate;
                txtWorkflowDescription.EditValue = detail.WorkflowDescription;
                txtConDetId.EditValue = detail.ConDetId;

                txtCustomField1.EditValue = String.Format("{0}", detail.CustomField1);
                txtCustomField2.EditValue = String.Format("{0}", detail.CustomField2);
                txtCustomField3.EditValue = String.Format("{0}", detail.CustomField3);
                txtCustomField4.EditValue = String.Format("{0}", detail.CustomField4);
                txtCustomField5.EditValue = String.Format("{0}", detail.CustomField5);
                
                grdDetail.DataSource = ClsWorkflow.ListDetail(MasterId);
            }


        }

        private void GetContractDetail(int conDetId)
        {
            var detail = ClsContractDetails.SelectByPk(conDetId);
            if (detail != null)
            {
                txtConDetCtManager.EditValue = detail.ConDetCtManager;
                txtConDetLeader.EditValue = detail.ConDetLeader;
                txtConDetStartDate.EditValue = detail.ConDetStartDate;
                txtConDetEndDate.EditValue = detail.ConDetEndDate;
                var contract = ClsContracts.SelectByPk(detail.ConId);
                txtConNo.EditValue = String.Format("{0}", contract.ConNo);
                txtConDate.EditValue = contract.ConDate;
                txtConName.EditValue = contract.ConName;
                txtConTypId.EditValue = contract.ConTypName;
                txtConPartA.EditValue = contract.ConPartAName;
                txtCatId.EditValue = contract.CatName;
                txtInsTypId.EditValue = contract.InsTypName;
                txtCapId.EditValue = contract.CapName;
                txtResId.EditValue = contract.ResName;
                txtConReceiptDate.EditValue = contract.ConReceiptDate;
                txtConAmount.EditValue = contract.ConAmount;
                txtConSetAmount.EditValue = contract.ConSetAmount;

                TaskSearchLookUpEdit.DataSource = ClsTask.ListDetail(conDetId);
                TaskSearchLookUpEdit.ValueMember = "TaskId";
                TaskSearchLookUpEdit.DisplayMember = "TaskName";

            } 
  

        }

        private void DoSave()
        {
            grdDetail.EmbeddedNavigator.Buttons.DoClick(grdDetail.EmbeddedNavigator.Buttons.EndEdit);

            #region "Variable"
            
            var dtSource = (DataTable)grdDetail.DataSource;

            #endregion

            #region "Check Condition"
            //if (!FormIsNotValidate)
            //{
            //    if (!dxValidationProvider.Validate())
            //    {
            //        XtraMessageBox.Show(
            //                    "Vui lòng nhập đầy đủ thông tin trước khi lưu",
            //                    "Thông báo",
            //                    MessageBoxButtons.OK,
            //                    MessageBoxIcon.Error);
            //        txtCode.SelectAll();
            //        txtCode.Focus();
            //        return;
            //    }
            //}
            if (dtSource.Rows.Count == 0)
            {
                XtraMessageBox.Show(
                            "Số lượng công việc trong hợp đồng phải >0.",
                            "Thông báo",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                txtConNo.SelectAll();
                txtConNo.Focus();
                return;
            }
            #endregion

            Entity.Base.Workflow item = MasterId <= 0 ? new Entity.Base.Workflow() : ClsWorkflow.SelectByPk(MasterId);
            item.WorkflowNo = String.Format("{0}", txtWorkflowNo.EditValue);
            item.WorkflowSymbol = String.Format("{0}", txtWorkflowSymbol.EditValue);
            item.WorkflowDate = txtWorkflowDate.DateTime;
            item.ConDetId = Convert.ToInt32(txtConDetId.EditValue);
            item.WorkflowDescription = String.Format("{0}", txtWorkflowDescription.EditValue);
           
            item.CustomField1 = String.Format("{0}", txtCustomField1.EditValue);
            item.CustomField2 = String.Format("{0}", txtCustomField2.EditValue);
            item.CustomField3 = String.Format("{0}", txtCustomField3.EditValue);
            item.CustomField4 = String.Format("{0}", txtCustomField4.EditValue);
            item.CustomField5 = String.Format("{0}", txtCustomField5.EditValue);
            
            item.FormId = FormNo;
            item.VoucherCate = VoucherCate;

            item.ListAdd = GetListAdd(dtSource.GetChanges(DataRowState.Added));
            item.ListUpdate = GetListUpdate(dtSource.GetChanges(DataRowState.Modified));
            item.ListDelete = GetListDelete(dtSource.GetChanges(DataRowState.Deleted));
            try
            {
                if (MasterId > 0)
                {
                    item.UpdateBy = ClsVariable.EmployeeId;
                    item.UpdateByName = ClsVariable.FullName;
                    item.UpdateDate = DateTime.Now;
                    ClsWorkflow.Update(item); 
                }
                else
                {
                    item.CreateBy = ClsVariable.EmployeeId;
                    item.CreateByName = ClsVariable.FullName;
                    item.CreateDate = DateTime.Now;
                    ClsWorkflow.Insert(item);
                    MasterId = item.WorkflowId;
                }
                
                dtSource.AcceptChanges();
                grdDetail.DataSource = ClsWorkflow.ListDetail(MasterId);
                if (SaveNew)
                {
                    MasterId = 0;
                    BlankForm();
                    txtWorkflowNo.Focus();
                }
                else if (SaveClose)
                {
                    Close();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                    String.Format("Có lỗi xảy ra trong quá trình cập nhật dữ liệu. {0}", ex.Message),
                    "Thông báo",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void DoDelete()
        {
            if (MasterId <= 0) return;
            
            try
            {
                if (
                        XtraMessageBox.Show(
                                        "Bạn có muốn xóa bản ghi này không?",
                                        "Thông báo",
                                        MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Question) == DialogResult.No) return;
                ClsWorkflow.DeleteByPk(MasterId);
                Close();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                       "Có lỗi xảy ra trong quá trình xóa dữ liệu. " + ex.Message,
                       "Thông báo",
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Error);
            }
        }

        private List<WorkflowDetails> GetListAdd(DataTable dataTable)
        {
            List<WorkflowDetails> list = new List<WorkflowDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    WorkflowDetails item = new WorkflowDetails();
                    item.WorkflowDetailId = 0;
                    item.TaskId = row["TaskId"] == DBNull.Value ? 0 : Convert.ToInt32(row["TaskId"]);
                    item.WorkflowDetailStatus = String.Format("{0}", row["WorkflowDetailStatus"]);
                    item.WorkflowDetailNumDay = row["WorkflowDetailNumDay"] == DBNull.Value ? 0 : Convert.ToInt32(row["WorkflowDetailNumDay"]);
                    if (!row.IsNull("WorkflowDetailBeginDate") && row["WorkflowDetailBeginDate"] != DBNull.Value)
                    {
                        item.WorkflowDetailBeginDate = Convert.ToDateTime(row["WorkflowDetailBeginDate"]);
                    }
                    if (!row.IsNull("WorkflowDetailEndDate") && row["WorkflowDetailEndDate"] != DBNull.Value)
                    {
                        item.WorkflowDetailEndDate = Convert.ToDateTime(row["WorkflowDetailEndDate"]);
                    }
                    if (!row.IsNull("EmpId") && row["EmpId"] != DBNull.Value)
                    {
                        item.EmpId = Convert.ToInt32(row["EmpId"]);
                    }
                    item.WorkflowDetailPercentComplete = row["WorkflowDetailPercentComplete"] == DBNull.Value ? 0 : Convert.ToDouble(row["WorkflowDetailPercentComplete"]);
                    item.WorkflowDetailDescription = String.Format("{0}", row["WorkflowDetailDescription"]);
                    list.Add(item);
                    
                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private List<WorkflowDetails> GetListUpdate(DataTable dataTable)
        {
            List<WorkflowDetails> list = new List<WorkflowDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    WorkflowDetails item = new WorkflowDetails();
                    item.WorkflowDetailId = Convert.ToInt32(row["WorkflowDetailId"]);
                    item.TaskId = row["TaskId"] == DBNull.Value ? 0 : Convert.ToInt32(row["TaskId"]);
                    item.WorkflowDetailStatus = String.Format("{0}", row["WorkflowDetailStatus"]);
                    item.WorkflowDetailNumDay = row["WorkflowDetailNumDay"] == DBNull.Value ? 0 : Convert.ToInt32(row["WorkflowDetailNumDay"]);
                    if (!row.IsNull("WorkflowDetailBeginDate") && row["WorkflowDetailBeginDate"] != DBNull.Value)
                    {
                        item.WorkflowDetailBeginDate = Convert.ToDateTime(row["WorkflowDetailBeginDate"]);
                    }
                    if (!row.IsNull("WorkflowDetailEndDate") && row["WorkflowDetailEndDate"] != DBNull.Value)
                    {
                        item.WorkflowDetailEndDate = Convert.ToDateTime(row["WorkflowDetailEndDate"]);
                    }
                    if (!row.IsNull("EmpId") && row["EmpId"] != DBNull.Value)
                    {
                        item.EmpId = Convert.ToInt32(row["EmpId"]);
                    }
                    item.WorkflowDetailPercentComplete = row["WorkflowDetailPercentComplete"] == DBNull.Value ? 0 : Convert.ToDouble(row["WorkflowDetailPercentComplete"]);
                    item.WorkflowDetailDescription = String.Format("{0}", row["WorkflowDetailDescription"]);

                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        private List<WorkflowDetails> GetListDelete(DataTable dataTable)
        {
            List<WorkflowDetails> list = new List<WorkflowDetails>();
            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                dataTable.BeginLoadData();
                foreach (DataRow row in dataTable.Rows)
                {
                    WorkflowDetails item = new WorkflowDetails();
                    item.WorkflowDetailId = Convert.ToInt32(row["WorkflowDetailId", DataRowVersion.Original]);
                    list.Add(item);

                }
                dataTable.EndLoadData();
            }
            return list;
        }

        #endregion

        #region "Background Worker"

        private void loadworker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                LstEmployees = ClsEmployees.SelectAll();
                DtContracts = ClsContracts.ListDetailByMbId(ClsVariable.MemberBranchId);
                e.Result = LstEmployees;
            }
            catch (Exception)
            {
                e.Cancel = true;
            }
        }

        private void loadworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Action a = LoadLookupData;
            txtInsTypId.Invoke(a);
            ClsVariable.SetWaitDialogCaption(string.Format("Danh sách {0} đã được nạp", Text));
        }
        #endregion

        #region "Form Event"
        private void FrmWorkflowDetailLoad(object sender, EventArgs e)
        {
            BlankForm();
            GetData();
            btnSaveNew.Enabled = !OnlyView;
            btnSave.Enabled = !OnlyView;
            btnSaveClose.Enabled = !OnlyView;
            btnDelete.Enabled = !OnlyView;
            btnDesign.Enabled = !OnlyView;
            if (!String.IsNullOrEmpty(FormXtraLayoutTemplate))
            {
                var fileLayout = ClsVariable.GetRestoreLayoutFullPath(FormXtraLayoutTemplate);
                layoutControl.RestoreLayoutFromXml(fileLayout);
            }
            if (String.IsNullOrEmpty(FormXtraGridLayoutTemplate)) return;
            var filePath = ClsVariable.GetRestoreLayoutFullPath(FormXtraGridLayoutTemplate);
            grvDetail.RestoreLayoutFromXml(filePath, DevExpress.Utils.OptionsLayoutBase.FullLayout);
        }
        #endregion

        #region "Toolbar Event"
        private void TbMenuItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "btnSave":
                    DoSave();
                    break;
                case "btnSaveNew"://Lưu và thêm mới
                    SaveNew = true;
                    DoSave();
                    break;
                case "btnSaveClose"://Lưu và đóng
                    SaveClose = true;
                    DoSave();
                    break;
                case "btnDelete":
                    DoDelete();
                    break;
                case "btnDesign":
                    ClsVariable.ShowDesignXtraGrid(grdDetail);
                    break;
                case "btnRefresh"://Nạp lại danh mục
                    GetData();
                    break;
                case "btnHistory"://History
                    break;
                case "btnClose":
                    Close();
                    break;
            }
        }
        #endregion

        #region "Lookup Edit"

        #endregion

        #region "XtraGrid Event"
        private void grvDetail_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Value == null) return;
            var view = (GridView)sender;

            switch (e.Column.FieldName)
            {
                case "TaskId"://Noi dung cong viec
                    int taskId = Convert.ToInt32(e.Value);
                    var item = ClsTask.GetTask(taskId);
                    if (item != null)
                    {
                        view.SetRowCellValue(e.RowHandle, "WorkflowDetailNumDay", item.TaskNumDay);
                        view.SetRowCellValue(e.RowHandle, "WorkflowDetailBeginDate", item.TaskBeginDate);
                        view.SetRowCellValue(e.RowHandle, "WorkflowDetailEndDate", item.TaskEndDate);
                        view.SetRowCellValue(e.RowHandle, "EmpId", item.EmpId);
                        
                    }
                    break;
            }
            
        }

        #endregion

        #region "TextEdit Event"
        private void txtConDetId_EditValueChanged(object sender, EventArgs e)
        {
            if (txtConDetId.EditValue != null)
            {
                int conDetId = Convert.ToInt32(txtConDetId.EditValue);
                GetContractDetail(conDetId);
            }
        }
        #endregion

        



    }
}
